﻿using AutoMapper;
using B.S.GridManager.Api.Write.Application.Command.PhsicalGrid;
using B.S.GridManager.ErrorCode;
using B.S.GridManager.Infrastructure.Interface;
using B.S.GridManger.Domain.Entities;
using MediatR;

namespace B.S.GridManager.Api.Write.Application.CommandHandler.PhsicalGrid
{
    /// <summary>
    /// 删除物理网格中介者处理类
    /// </summary>
    public class DelPhysicalGridHandler : IRequestHandler<DelPhysicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PhysicalGridModel> physicalRepo;
        private readonly ILogger<UpdatePhsicalGridHandler> logger;
        private readonly IMapper mapper;

        /// <summary>
        /// 通过构造函数注入对象
        /// </summary>
        /// <param name="physicalRepo">物理网格仓储</param>
        /// <param name="logger">日志组件</param>
        /// <param name="mapper">映射组件</param>
        public DelPhysicalGridHandler(IBaseRepository<PhysicalGridModel> physicalRepo, ILogger<UpdatePhsicalGridHandler> logger, IMapper mapper) {
            this.physicalRepo = physicalRepo;
            this.logger = logger;
            this.mapper = mapper;
        }


        /// <summary>
        /// 逻辑删除物理网格的处理方法
        /// </summary>
        /// <param name="request">删除请求参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>Task包装的响应包装类</returns>
        public Task<ApiResult<int>> Handle(DelPhysicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            logger.LogInformation("您即将要删除的物理网格:" + request.Id);
            var entity = physicalRepo.GetModel(request.Id);
            if (entity == null) {
                result.Code = ApiEnums.Error;
                result.Msg = "您要删除的物理网格不存在";
                logger.LogError("您要删除的物理网格不存在:" + request.Id);

                return Task.FromResult(result); 
            }

            entity.IsDeleted = true;

            int r = physicalRepo.Update(entity);
            if (r > 0)
            {
                result.Code = ApiEnums.Success;
                result.Msg = "删除成功!";
                result.Data = r;
                logger.LogInformation("您已成功删除物理网格:" + request.Id);
            }
            else
            {
                result.Code = ApiEnums.Fail;
                result.Msg = "删除失败!";
                result.Data = r;
                logger.LogInformation("您未成功删除物理网格:" + request.Id);
            }

            return Task.FromResult(result);
        }
    }
}
